#!/bin/bash

op=
param=
target=

ADMIN_RC="/etc/kolla/admin-openrc.sh"

if [ "$1" == "install" ]; then
    op=install
    docker cp $ADMIN_RC kolla_toolbox:/ || exit -1
elif [ "$1" == "check" ]; then
    op=check
elif [ "$1" == "clean" ]; then
    op=check
    param="-k"
else
    echo "$0 <install|check|clean> [node]" >&1
    exit -1
fi
shift
target=$1

install() {
    local node=$1
    scp vmchecker prickvm root@$node:/tmp/
    echo "$node /tmp/vmchecker /tmp/prickvm"
    ssh root@$node docker cp /tmp/vmchecker nova_libvirt:/
    ssh root@$node docker cp /tmp/prickvm nova_libvirt:/
    echo "$node nova_libvirt:/vmchecker nova_libvirt:/prickvm"
}

check() {
    local node=$1
    local clean=$2

    echo "checking on $node"
    ssh root@$node docker exec nova_libvirt /bin/bash /vmchecker $clean || \
      echo -e "run \"$0 install\"" >&1
}

rundir=$(dirname $0)
cd $rundir

get_active_compute_nodes() {
    local node=
    IFS=$'\n'
    for x in $(docker exec -it kolla_toolbox \
     /bin/bash -c ". /admin-openrc.sh && \
     openstack compute service list --service nova-compute \
     -c Host -c State -f value|grep up"); do
        unset IFS
        read node tmp <<< $x
        echo -n "$node "
    done
}

if [ -z "$target" ]; then
     target="$(get_active_compute_nodes)"
fi

for x in $target;do
    $op $x $param
done

